package services.lmpl;

import entity.LoginUser;
import services.LoginUserService;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class LoginUserServiceImpl implements LoginUserService {

    public static void writeLoginMsg(LoginUser loginUser) throws IOException {
        DataOutputStream output = new DataOutputStream(new FileOutputStream("information/"+loginUser.getName()+".dat"));
        output.writeUTF(loginUser.getName());
        output.writeUTF(loginUser.getPassword());
    }

    public static LoginUser readLoginMsg(String name) {
        try{
            DataInputStream input = new DataInputStream(new FileInputStream("information/"+name+".dat"));
            return new LoginUser(input.readUTF(),input.readUTF());
        }catch (IOException e){
            return null;
        }
    }

    @Override
    public LoginUser checkOne(String name, String passwd){
        LoginUser loginUser = readLoginMsg(name);
        if((loginUser == null) || !(passwd.equals(loginUser.getPassword()))) {
            return null;
        }
        return loginUser;
    }

    @Override
    public int updateUserById(String name, String passwd) throws IOException {
        LoginUser loginUser = new LoginUser(name, passwd);
        try {
            writeLoginMsg(loginUser);
        }catch (IOException e){
            return 0;
        }
        return 1;
    }
}
